package com.zcr.config.etc;


import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @version 1.0
 * @author： 张诚
 * @date： 2021-01-29 10:58
 */
@Configuration
public class ShiroConfig {

    @Resource
    private DbReam dbReam;

    @Bean
    public DefaultWebSecurityManager securityManager(){
        DefaultWebSecurityManager defaultWebSecurityManager=new DefaultWebSecurityManager();
//        dbReam.setCredentialsMatcher(credentialsMatcher());
        defaultWebSecurityManager.setRealm(dbReam);
        return defaultWebSecurityManager;
    }

    @PostConstruct
    public void init(){
        SecurityUtils.setSecurityManager(securityManager());
    }

    public HashedCredentialsMatcher credentialsMatcher(){
        HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();
        credentialsMatcher.setHashAlgorithmName("md5");
        credentialsMatcher.setHashIterations(1);
        return  credentialsMatcher;
    }
//
    @Bean(name="shiroFilter")
    public ShiroFilterFactoryBean shiroFilterFactoryBean(){
        ShiroFilterFactoryBean shiroFilter=new ShiroFilterFactoryBean();
        shiroFilter.setSecurityManager(securityManager());
        shiroFilter.setUnauthorizedUrl("/login");
        Map<String,String> filterChainDefinition = new LinkedHashMap<>();
        filterChainDefinition.put("/login","anon");
        filterChainDefinition.put("/webjars/**","anon");
        filterChainDefinition.put("/static/**","anon");
//        filterChainDefinition.put("/ldasodokas","perms[a:a]");
        filterChainDefinition.put("/logout","logout");
        filterChainDefinition.put("/**","authc");
        shiroFilter.setFilterChainDefinitionMap(filterChainDefinition);
        shiroFilter.setLoginUrl("/login");
        return shiroFilter;
    }


}
